// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({    env: "dzc-aapp-0g1mx02g41e97626", }) // 使用当前云环境

// 云函数 joinActivity
// 云函数 joinActivity
exports.main = async (event, context) => {
  const { activityId, userId, action } = event;
  const db = cloud.database();
  const _ = db.command;
  
  try {
    // 更新参与者列表
    if (action === 'join') {
      await db.collection('activities').doc(activityId).update({
        data: {
          participants: _.push(userId)
        }
      });
    } else {
      await db.collection('activities').doc(activityId).update({
        data: {
          participants: _.pull(userId)
        }
      });
    }
    
    // 获取更新后的参与者列表
    const res = await db.collection('activities').doc(activityId).get();
    const updatedParticipants = res.data.participants || [];
    
    return {
      success: true,
      updatedParticipants
    };
  } catch (err) {
    return {
      success: false,
      error: err.message
    };
  }
};